<template>
    <div>
        <el-form :inline="true" :model="queryParam" class="demo-form-inline">
            <el-form-item label="服务名称">
                <el-input size="mini" clearable v-model="queryParam.name" placeholder="输入服务名称"></el-input>
            </el-form-item>
            <el-form-item label="服务状态">
                <el-select size="mini" clearable v-model="queryParam.state" placeholder="服务状态">
                    <el-option label="下架" value="0"></el-option>
                    <el-option label="上架" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                        value-format="yyyy-MM-dd"
                        size="mini"
                        v-model="queryParam.dateParam"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button size="mini" type="primary" @click="toQuery">查询</el-button>
                <el-button size="mini" type="success" @click="openSaveWin">添加</el-button>
                <el-button size="mini" type="warning" @click="updateState(1)">上架</el-button>
                <el-button size="mini" type="default" @click="updateState(0)">下架</el-button>
            </el-form-item>
        </el-form>
        <el-table
                ref="multipleTable"
                :data="tableData"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    label="服务名称" prop="name">
            </el-table-column>
            <el-table-column
                    label="服务图片">
                <template slot-scope="scope">
                    <el-image :src="scope.row.resourcesUrls==null?'':scope.row.resourcesUrls.split(',')[0]"
                              :preview-src-list="scope.row.resourcesUrls==null?'':scope.row.resourcesUrls.split(',')"></el-image>
                </template>
            </el-table-column>
            <el-table-column
                    prop="saleprice"
                    label="服务价格">
            </el-table-column>
            <el-table-column prop="onsaletime" label="上架时间"></el-table-column>
            <el-table-column prop="offsaletime" label="下架时间"></el-table-column>
            <el-table-column label="状态" prop="state">
                <template slot-scope="scope">
                    <el-tag type="danger" v-if="scope.row.state==0">下架</el-tag>
                    <el-tag type="warning" v-else-if="scope.row.state == 1">上架</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                    prop="costprice"
                    label="零售价">
            </el-table-column>
            <el-table-column
                    fixed="right"
                    label="操作"
                    width="100">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="modifyInitData(scope.row.id)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @current-change="handleCurrentChange"
                :current-page="queryParam.currentPage"
                :page-size="queryParam.pageSize"
                background
                layout="prev, pager, next"
                :total="total">
        </el-pagination>

        <!--新增/修改弹出框 fullscreen：将弹框设置为全屏-->
        <el-dialog :title="title" :visible.sync="addFormVisible" fullscreen>
            <!--
                ref:简单理解就是申明form表单的id
                :rules:定义校验规则
             -->
            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="服务" prop="product.name">
                    <el-input v-model="form.product.name"></el-input>
                </el-form-item>
                <el-form-item prop="logo" label="服务图片">
                    <el-upload
                            class="upload-demo"
                            action="http://localhost/file/upload"
                            :on-success="handleSuccess"
                            :file-list="fileList"
                            list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="成本价" prop="product.costprice">
                    <el-input v-model="form.product.costprice"></el-input>
                </el-form-item>
                <el-form-item label="售价">
                    <el-input v-model="form.product.saleprice"></el-input>
                </el-form-item>
                <el-form-item label="服务详情">
                    <!-- <el-input v-model="form.intro"></el-input>-->
                    <quill-editor :options="editorOption" v-model="form.productDetail.intro">
                    </quill-editor>
                </el-form-item>
                <el-form-item label="预约须知">
                    <quill-editor :options="editorOption" v-model="form.productDetail.orderNotice">
                    </quill-editor>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="width: 100%;text-align: center">
                <el-button size="mini" style="width: 40%" @click.native="addFormVisible = false">取消</el-button>
                <el-button size="mini" style="width: 40%" type="primary" @click="save('form')">提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import {quillEditor} from "vue-quill-editor"; //调用编辑器
    import 'quill/dist/quill.core.css';
    import 'quill/dist/quill.snow.css';
    import 'quill/dist/quill.bubble.css';
    import quillConfig from "@/common/quill-config" //对当前这个富文本编辑器的配置。主要配置的就是编辑器中的按钮功能

    export default {
        //申明组件
        components: {
            quillEditor
        },
        data() {
            return {
                editorOption: quillConfig,
                /*定义校验规则*/
                rules: {
                    product: {
                        name: [
                            {required: true, message: '服务名必填!!', trigger: 'blur'}
                        ],
                        costprice: [
                            {required: true, message: '成本价格必填!!', trigger: 'blur'}
                        ]
                    }

                },
                fileList: [],//上传的文件列表:
                //弹出框标题
                title: "",
                //弹出框默认是关闭状态
                addFormVisible: false,
                form: {
                    product: {},
                    productDetail: {},
                    resources: [] //保存指定上传的文件URL（不带前缀）
                },
                queryParam: {
                    currentPage: 1,
                    pageSize: 10 //这里只能设置10，因为现在用的简化版分页组件
                },
                total: 0,
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                tableData: [],
                multipleSelection: [] //获取复选框中所有选中的数据
            }
        },
        methods: {
            //下架或下架操作
            updateState(state) {
                this.$confirm('是否继续此操作?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.get("/product/updateState?ids=" + this.multipleSelection.join(",") + "&state=" + state).then(res => {
                        if (res.data.success) {
                            this.toQuery();
                        }
                    })
                })
            },
            //打开新增窗口时的处理
            openSaveWin() {
                this.addFormVisible = true
                //重新打开新增窗口时，需要将界面中的数据清空
                this.form = {
                    product: {},
                    productDetail: {},
                    resources: [] //保存指上传的文件URL（不带前缀）
                }
                this.fileList = [];
            },
            //编辑操作前，先到后台查询最新数据
            modifyInitData(id) {
                //打开编辑窗口前，先清空el-upload中的数据
                this.fileList = [];
                //理由：因为列表中展示的数据和  编辑时，回显的数据并不是来自同一张表（实体）
                //就需要在打开编辑 窗口时，就需要重新查询数据并对数据进行初始化修改
                this.$http.get("/product/" + id).then(res => {
                    this.form = res.data;
                    //对关于el-upload组件中图片的回显处理初始化操作
                    this.form.resources = this.form.product.resources ? this.form.product.resources.split(",") : [];
                    let resourcesUrls = this.form.product.resourcesUrls.split(",");
                    for (let index in resourcesUrls) {
                        //el-upload组件需要初始化的数据源
                        this.fileList.push({url: resourcesUrls[index]})
                    }
                    this.addFormVisible = true;
                })

            },

            //当图片上传成功后，会回调这个方法。
            //参数1：响应的结果；参数2：当前上传的文件；参数3：上传的文件列表
            handleSuccess(response, file, fileList) {
                console.log(">>>>>>response=" + JSON.stringify(response) + ",file=" + file)
                //将添加成功后的图片URL保存到 filelist（el-upload如果是本地上传操作，上传成功后，不需要向数据源filelist中添加图片url）
                    //默认读的是本地上传的文件的本地路径
                console.log(">>>>>>>>>>>>"+JSON.stringify(this.fileList))
                this.form.resources.push(response.data);
            },
            save(form) {
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        //校验通过
                        //执行保存操作前，先将上传的图片列表，设置form表单对象中
                        this.form.product.resources = this.form.resources.toString();
                        console.log(">>>>>>>>this.form.resources" + this.form.resources + ",fileList=" + this.fileList);
                        this.$http.post("/product/save", this.form).then(res => {
                            if (res.data.success) {
                                //还需关闭当前弹框，现时清空数据
                                this.form = {
                                    product: {},
                                    productDetail: {}
                                }
                                this.addFormVisible = false;
                                this.toQuery();
                            }
                            //无论成功还是失败，都给个提示
                            this.$notify({
                                title: '操作提示',
                                message: h('i', {style: 'color: teal'}, res.data.message)
                            });
                        })
                    }
                })
            },
            toQuery() {
                console.log(">>>>>>>>>>>>输出查询条件：" + JSON.stringify(this.queryParam));
                //发送请求，并携带查询条件
                this.$http.post("/product", this.queryParam).then(res => {
                    this.tableData = res.data.data;
                    this.total = res.data.total;
                })
            },
            handleSelectionChange(val) {
                console.log(">>>>>>>>>>" + JSON.stringify(val))
                let that = this;
                this.multipleSelection = [];
                val.forEach(function (value) {
                    that.multipleSelection.push(value.id);
                })
            },
            handleCurrentChange(val) {
                this.queryParam.currentPage = val;
                this.toQuery();
            }
        },
        mounted() {
            this.toQuery();
        }
    }
</script>
<style>
    .quill-editor {
        height: 10px;
    }
</style>
